package com.qianbei.view.transport;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.security.mobile.module.commonutils.LOG;
import com.google.gson.Gson;
import com.qianbei.R;
import com.qianbei.bean.GetBoxBody;
import com.qianbei.bean.GetBoxBody1;
import com.qianbei.bean.GetCouseBean;
import com.qianbei.bean.GetEmpty_Body;
import com.qianbei.bean.GetUpbox;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.view.EpcDataBase;
import com.qianbei.view.GetCarActivity;
import com.qianbei.view.adapter.ScanAdapter;
import com.qianbei.view.binding.AddBingActivity;
import com.qianbei.view.db.BoxDb;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RFID;
import com.qianbei.view.orm.RFIDDao;
import com.qianbei.view.orm.RequestPersistent;
import com.qianbei.view.util.JobBoxUtil;
import com.qianbei.view.util.MessageCallback;
import com.speedata.libuhf.IUHFService;
import com.speedata.libuhf.UHFManager;
import com.speedata.libuhf.bean.SpdInventoryData;
import com.speedata.libuhf.interfaces.OnSpdInventoryListener;

import org.greenrobot.greendao.query.QueryBuilder;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTouch;

/**
 * Created by gaoml on 2018/1/17.
 */

public class EmptyUPActivity extends BaseActivity {


    private static final String TAG = EmptyUPActivity.class.getSimpleName();
    private int init_progress = 0;
    private PowerManager pM = null;
    private PowerManager.WakeLock wK = null;


    private IUHFService iuhfService;
    private ListView EpcList;
    private TextView Status;
    private List<EpcDataBase> firm = new ArrayList<EpcDataBase>();

    private ScanAdapter adapter;

    @Bind(R.id.boxnumber)
    public EditText boxnum;

    @Bind(R.id.finish_scan)
    TextView finishButton;

    @Bind(R.id.scan_stat_info)
    TextView scanStat;
    /**
     * 客户ID
     */
    private String id;//cus_id:  收运接口1中的 customerAry 内部的 id  (客户ID)
    /**
     * full empty
     */
    private String type;

    private boolean empty;

    /**
     * 是否上电状态
     */
    private AtomicBoolean isOpenDev = new AtomicBoolean(false);
    /**
     * 成功上电
     */
    private AtomicBoolean isOpenSucces = new AtomicBoolean(false);

    /**
     *
     */
    private Set<String> alreadySave = new HashSet<String>();
    private RFIDDao rfidDao;

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);

    private AtomicBoolean canRead = new AtomicBoolean(false);

    private BoxDb boxDb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gufei_boxup_full_activity);

        ButterKnife.bind(this);

        boxDb = new BoxDb(this);

        id = getIntent().getStringExtra("id");
        type = getIntent().getStringExtra("box");

        if (type.equals("empty")) {
            empty = true;
        } else {
            empty = false;
        }

        EpcList = (ListView) findViewById(R.id.listView_search_epclist);
        Status = (TextView) findViewById(R.id.textView_search_status);

        adapter = new ScanAdapter(
                this, firm, R.layout.gufei_item_scan);

        EpcList.setAdapter(adapter);

        adapter.setStatus(Status);
        adapter.setStat(scanStat);
        adapter.setShortTxt(true);
        adapter.setDelCallback(new MessageCallback(){
            @Override
            public void call() {
                updateStatus();
            }
        });

        findViewById(R.id.save).setOnClickListener(this);
        findViewById(R.id.boxnum_add).setOnClickListener(this);
        findViewById(R.id.scan_stat).setVisibility(View.GONE);

        if (!type.equals("full")) {
            setTitle("空箱子装卸扫描");
            findViewById(R.id.boxnum_load).setVisibility(View.GONE);
        } else {
            setTitle("重箱子装卸扫描");
        }

        mTitle.setrightTitle("完成扫描");
        if (TextUtils.isEmpty(SetData.getCarId())) {
            startActivity(GetCarActivity.class);
            new MsgAlert().show("请先绑定车辆");
            finish();
        }

        initUHFService();

        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
        rfidDao = daoSession.getRFIDDao();
    }

    private void initUHFService() {
        iuhfService = MyApplication.iuhfService;


        newWakeLock();


    }

    private void newWakeLock() {
        init_progress++;
        pM = (PowerManager) getSystemService(POWER_SERVICE);
        if (pM != null) {
            wK = pM.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, "lock3992");
            if (wK != null) {
                wK.acquire();
                init_progress++;
            }
        }
        if (init_progress == 1) {
            Log.w("3992_6C", "wake lock init failed");
        }
    }

    boolean ishow = false;
    EpcDataBase b;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            Log.d("gaoaa", "EmptyUPActivity_"+msg.what);
            switch (msg.what) {
                case 111:
                    SpdInventoryData var1 = (SpdInventoryData) msg.obj;
//                    Log.d("gaoaa", "EmptyUPActivity226"+var1.epc +",,,firm.size():"+firm.size());

                    int j;
                    for (j = 0; j < firm.size(); j++) {
                         if (var1.epc.equals(firm.get(j).epc)) {
                            firm.get(j).valid++;
                            firm.get(j).setRssi(var1.rssi);
                            break;
                        }
                    }
                    if (j == firm.size()) {

                        final EpcDataBase epcDataBase = new EpcDataBase(var1.epc, 1,
                                var1.rssi, var1.tid);

                        if (canRead.getAndSet(false)) {
                            firm.clear();

                            ring();
                            mTitle.setrightTitle("完成扫描");
                            iuhfService.newInventoryStop();

                            try {
                                JobBoxUtil.getBoxType(boxDb, epcDataBase, new MessageCallback() {
                                    @Override
                                    public void call() {

                                        QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                                        // 指定派车单 指定客户 指定箱子类型 条件查询
                                        qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.Rfid.eq(epcDataBase.epc), RFIDDao.Properties.WhichStep.eq("BoxLoadAndUnload"),
                                                RFIDDao.Properties.CustomerId.eq(id), RFIDDao.Properties.Empty.eq(empty)));
                                        if (TextUtils.isEmpty(epcDataBase.boxId)) {
                                            new MsgAlert().show("rfid与箱号未绑定");
                                            return;
                                        }
                                        List<RFID> queryRfid = qb.list();
                                        if (queryRfid.size() == 0) {

                                            RFID rfid = new RFID();
                                            rfid.setRfid(epcDataBase.epc);
                                            rfid.setJobId(SetData.getJobid());
                                            rfid.setCustomerId(id);
                                            rfid.setWhichStep("BoxLoadAndUnload");
                                            rfid.setBoxNum(epcDataBase.boxId);
                                            rfid.setBoxType(epcDataBase.boxType);

                                            if (!TextUtils.isEmpty(epcDataBase.typeValue)) {
                                                rfid.setBoxTypeIntVal(Integer.valueOf(epcDataBase.typeValue));
                                            }

                                            rfid.setEmpty(empty);

                                            rfidDao.save(rfid);

                                        } else {
                                            RFID rfid = queryRfid.get(0);
                                            rfid.setBoxNum(epcDataBase.boxId);
                                            rfid.setBoxType(epcDataBase.boxType);

                                            if (!TextUtils.isEmpty(epcDataBase.typeValue)) {
                                                rfid.setBoxTypeIntVal(Integer.valueOf(epcDataBase.typeValue));
                                            }

                                            rfidDao.update(rfid);
                                        }

                                        firm.clear();

                                        firm.add(0, epcDataBase);
                                        adapter.notifyDataSetChanged();
                                        updateStatus();


                                    }
                                });
                            }catch (Exception e){

                            }
                        }
                    }

                    adapter.notifyDataSetChanged();

                    //Status.setText("扫描数量: " + firm.size());
                    break;

                case 2:
                    mTitle.setrightTitle("完成扫描");
                    iuhfService.newInventoryStop();
                    break;
            }
        }
    };

    /**
     * 上电开串口
     *
     * @return
     */
    private boolean openDev() {
        int openDevStatus = iuhfService.OpenDev();
        Log.d("BoxUpOpenDevFlag", openDevStatus + "");
        if (openDevStatus != 0) {
            new android.app.AlertDialog.Builder(this).setTitle(R.string.DIA_ALERT).setMessage(R.string.DEV_OPEN_ERR).setPositiveButton(R.string.DIA_CHECK, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    finish();
                }
            }).show();
            return true;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();

        mTitle.setrightTitle("完成扫描");

        isOpenDev.set(false);
        iuhfService.setOnInventoryListener(new OnSpdInventoryListener() {
            @Override
            public void getInventoryData(SpdInventoryData var1) {
                handler.sendMessageDelayed(handler.obtainMessage(111, var1), 1000);
            }
        });

        if (!TextUtils.isEmpty(SetData.getJobid()) && !TextUtils.isEmpty(id)) {
            Log.d("JobSavedRFID", SetData.getJobid());

            if (firm != null && firm.size() > 0) {
                for (final EpcDataBase epcDataBase : firm) {
                    JobBoxUtil.getBoxType(boxDb, epcDataBase, new MessageCallback() {
                        @Override
                        public void call() {
                            QueryBuilder<RFID> qb = rfidDao.queryBuilder();

                            if (!TextUtils.isEmpty(epcDataBase.epc)) {
                                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxLoadAndUnload"),
                                        RFIDDao.Properties.CustomerId.eq(id), RFIDDao.Properties.Rfid.eq(epcDataBase.epc), RFIDDao.Properties.Empty.eq(empty)));
                            } else {
                                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxLoadAndUnload"),
                                        RFIDDao.Properties.CustomerId.eq(id), RFIDDao.Properties.BoxNum.eq(epcDataBase.boxId), RFIDDao.Properties.Empty.eq(empty)));
                            }
                            List<RFID> queryRfid = qb.list();

                            if (queryRfid.size() == 1) {
                                RFID rfid = queryRfid.get(0);
                                rfid.setRfid(epcDataBase.epc);
                                rfid.setBoxNum(epcDataBase.boxId);
                                rfid.setBoxType(epcDataBase.boxType);
                                if (!TextUtils.isEmpty(epcDataBase.typeValue)) {
                                    rfid.setBoxTypeIntVal(Integer.valueOf(epcDataBase.typeValue));
                                }
                                rfidDao.update(rfid);
                            }

                        }
                    });
                }

                Collections.sort(firm);
            }

        }

        adapter.notifyDataSetChanged();
        updateStatus();

    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (iuhfService != null && isOpenDev.get() == true) {
                iuhfService.newInventoryStop();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            if (iuhfService != null && isOpenDev.get() == true) {
                iuhfService.newInventoryStop();
                //断电后选卡操作会失效，需要重新选卡（掩码）
                iuhfService.CloseDev();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:
                finishScan(findViewById(R.id.tv_right));

                break;
            default:
                break;
        }

    }


    @SuppressLint("StaticFieldLeak")
    @OnTouch(R.id.finish_scan)
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
//                if(checkBox()){
//                    new MsgAlert().show("已扫描的箱子信息不完整，请补全后再试");
//                    return false;
//                }


                Log.d("touchEven", "down");
                Log.d("fClick:", isOpenDev.get() + "");
                vibrate();
                finishButton.setBackgroundColor(getResources().getColor(R.color.color_4d9dce));
                mTitle.setrightTitle("扫描中...");
                //重复点扫描按钮时 只做一次上电操作
                if (isOpenDev.get() == false) {
                    isOpenDev.set(true);
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... voids) {
                            try {
                                if (openDev()) {
                                    isOpenDev.set(false);
                                    return null;
                                } else {
                                    isOpenSucces.set(true);
                                }
                                iuhfService.set_antenna_power(MyApplication.setValue);
                            } catch (Exception e) {
                                e.printStackTrace();
                                isOpenDev.set(false);
                                return null;
                            }
                            iuhfService.newInventoryStart();
                            canRead.set(true);
                            return null;
                        }
                    }.execute();

                } else if (isOpenSucces.get() == true) {
                    iuhfService.newInventoryStart();
                    canRead.set(true);
                }
                break;
            case MotionEvent.ACTION_UP:
                Log.d("touchEven", "up");
                finishButton.setBackgroundColor(getResources().getColor(R.color.color_519DCC));
                mTitle.setrightTitle("完成扫描");
                if (isOpenSucces.get() == true) {
                    iuhfService.newInventoryStop();
                } else {
                    delayStop();
                }
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {

            case R.id.save:
//                if (firm.size() > 0) {
                    confirmFinish();
//                }

                break;
            case R.id.boxnum_add:
                boxnumAdd();
                break;
            default:
                break;
        }
    }

    public void confirmFinish() {
//        if(checkBox()){
//            new MsgAlert().show("已扫描的箱子信息不完整，请补全后再试");
//            return;
//        }

        String str = "确认保存吗？";
        if(!checkBoxE()&& !type.equals("full")){
            str = "周转箱数量为0，您确定要保存？";
        }
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage(str)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        updateLoad();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    /**
     * 更新扫描大小箱计数
     */
    private void updateStatus() {
        try {
            if(!TextUtils.isEmpty(SetData.getJobid()) && !TextUtils.isEmpty(id)){
                QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxLoadAndUnload"),
                        RFIDDao.Properties.CustomerId.eq(id), RFIDDao.Properties.Empty.eq(empty)));
                List<RFID> queryRfid = qb.list();

                JobBoxUtil util = new JobBoxUtil();
                String count = util.countBox(queryRfid, false);
                if (count!=null){
                    Status.setText(count);
                    scanStat.setText(count);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.finish_scan)
    public void finishScan(View view) {
        findViewById(R.id.scan_stat).setVisibility(View.VISIBLE);
        findViewById(R.id.save).setVisibility(View.VISIBLE);
        findViewById(R.id.finish_scan).setVisibility(View.GONE);
        findViewById(R.id.boxnum_load).setVisibility(View.GONE);


        if (!TextUtils.isEmpty(SetData.getJobid()) && !TextUtils.isEmpty(id)) {
            QueryBuilder<RFID> qb = rfidDao.queryBuilder();
            qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxLoadAndUnload"),
                    RFIDDao.Properties.CustomerId.eq(id), RFIDDao.Properties.Empty.eq(empty)));


            List<RFID> queryRfid = qb.list();

            if (queryRfid.size() > 0) {
                for (RFID rfid : queryRfid) {
                    EpcDataBase epcDataBase = new EpcDataBase(rfid.getRfid(), 1,
                            "", "");
                    epcDataBase.setBoxId(rfid.getBoxNum());
                    epcDataBase.setEpc(rfid.getRfid());
                    epcDataBase.setBoxType(rfid.getBoxType());
                    epcDataBase.setTypeValue(rfid.getBoxTypeIntVal() + "");

                    if (!firm.contains(epcDataBase)) {
                        firm.add(epcDataBase);
                    }
                }

            }
        }

        Collections.sort(firm);

        adapter.notifyDataSetChanged();
        adapter.updateStatusText(false);
        adapter.updateStat();

    }

    private void ring() {


        Uri notification = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.beep_once);
        if (notification == null) return;
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

        Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(500);
    }

    private void vibrate(){
        Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(100);
    }

    private void delayStop() {

        handler.sendEmptyMessageDelayed(2, 5000);

    }

    /**
     * 按箱号添加
     */
    public void boxnumAdd() {
        String boxNum = ((EditText) findViewById(R.id.boxnumber)).getText().toString();
        Log.d("BoxNumberAdd", boxNum);
        if (TextUtils.isEmpty(boxNum)) {
            new MsgAlert().show("请输入箱子编号");
            return;
        }

        boxNum = boxNum.trim();
        final EpcDataBase epc = new EpcDataBase("", 1,
                "", "");
        epc.setBoxType("");
        epc.setBoxId(boxNum);


        final String finalBoxNum = boxNum;
        JobBoxUtil.getBoxType(boxDb, epc, new MessageCallback() {
            @Override
            public void call() {
                QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                // 指定派车单 指定客户 指定箱子类型 条件查询
                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.BoxNum.eq(finalBoxNum), RFIDDao.Properties.WhichStep.eq("BoxLoadAndUnload"),
                        RFIDDao.Properties.CustomerId.eq(id), RFIDDao.Properties.Empty.eq(empty)));

                List<RFID> queryRfid = qb.list();
                if (queryRfid.size() == 0) {

                    RFID rfid = new RFID();
                    rfid.setJobId(SetData.getJobid());
                    rfid.setWhichStep("BoxLoadAndUnload");
                    rfid.setCustomerId(id);
                    rfid.setBoxNum(epc.boxId);
                    rfid.setBoxType(epc.boxType);
                    rfid.setEmpty(empty);
                    rfid.setRfid(epc.epc);
                    if (!TextUtils.isEmpty(epc.typeValue)) {
                        rfid.setBoxTypeIntVal(Integer.valueOf(epc.typeValue));
                    }

                    rfidDao.save(rfid);

                } else {
                    RFID rfid = queryRfid.get(0);
                    rfid.setBoxNum(epc.boxId);
                    rfid.setRfid(epc.epc);
                    rfid.setBoxType(epc.boxType);
                    if (!TextUtils.isEmpty(epc.typeValue)) {
                        rfid.setBoxTypeIntVal(Integer.valueOf(epc.typeValue));
                    }

                    rfidDao.update(rfid);
                }

                firm.clear();

                firm.add(0, epc);
                adapter.notifyDataSetChanged();
                updateStatus();

                ((EditText) findViewById(R.id.boxnumber)).setText("");

            }
        });


        new MsgAlert().show("添加成功");

    }
//

    /**
     *
     */
    private void updateLoad() {
        ArrayList<String> where = new ArrayList<>();
        ArrayList<String> boxNum = new ArrayList<>();
        int big = 0;
        int small = 0;
        for (EpcDataBase a : firm) {
            if (a.getEpc() != null && a.getEpc().trim().length() > 0) {
                where.add(a.epc);
            } else if (a.boxId != null && a.boxId.trim().length() > 0) {
                boxNum.add(a.boxId);
            }
            if (TextUtils.equals("1", a.typeValue) || TextUtils.equals("3", a.typeValue)) {
                small++;
            } else if (TextUtils.equals("2", a.typeValue) || TextUtils.equals("4", a.typeValue)) {
                big++;
            }
        }
        SharedPreferences pref = getSharedPreferences("isOver",0);
        SharedPreferences.Editor editor =  pref.edit();
        String data_id = "id"+id;
        editor.putBoolean(data_id,true).commit();


        RequeastBean bean = new RequeastBean("select", "com.cygps.dubbo.WasteTransport.IPdaBoxnullAndLoadandunloadScan",
                new GetEmpty_Body(where, id, type, boxNum));

        if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存
//            MyApplication.netList.add(bean); bug001
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(GetEmpty_Body.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            //new MsgAlert().show("现在没用网络，数据已保存 有网络的时候会自动提交");
            handler.removeCallbacksAndMessages(null);
            Intent mIntent = new Intent();
            mIntent.putExtra("big",big );
            mIntent.putExtra("small",small);
            // 设置结果，并进行传送
            EmptyUPActivity.this.setResult(0, mIntent);
            finish();

        } else {

            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {

                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        iuhfService.newInventoryStop();
                        JSONObject jsonObject = sr.bodyData.optJSONObject("count");
                        Intent mIntent = new Intent();
                        mIntent.putExtra("big", jsonObject.optString("big"));
                        mIntent.putExtra("small", jsonObject.optString("small"));
                        // 设置结果，并进行传送
                        EmptyUPActivity.this.setResult(0, mIntent);
                        finish();
                    }

                }
            };

            new ProgressDialog(mContext).OKpost(sc);
        }

    }


    /**
     * 检查是否存在数据不全的箱子
     * 有数据不全的箱子返回true
     */
    private Boolean checkBox () {
        Boolean flag = false;
        if(!TextUtils.isEmpty(SetData.getJobid()) && !TextUtils.isEmpty(id)){
            QueryBuilder<RFID> qb = rfidDao.queryBuilder();
            qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxLoadAndUnload"),
                    RFIDDao.Properties.CustomerId.eq(id), RFIDDao.Properties.Empty.eq(empty)));
            List<RFID> queryRfid = qb.list();
            if(queryRfid.size()==0){
                return false;
            }
            for(RFID r:queryRfid){
                if(TextUtils.isEmpty(r.getBoxNum())||TextUtils.isEmpty(r.getBoxType())){
                    flag = true ;
                    break;
                }
            }
        }
        return flag;
    }
    /**
     * 检查是否扫描了空箱子
     */
    private Boolean checkBoxE () {
        Boolean flag = true;
        if(!TextUtils.isEmpty(SetData.getJobid()) && !TextUtils.isEmpty(id)){
            QueryBuilder<RFID> qb = rfidDao.queryBuilder();
            qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxLoadAndUnload"),
                    RFIDDao.Properties.CustomerId.eq(id), RFIDDao.Properties.Empty.eq(empty)));
            List<RFID> queryRfid = qb.list();
            if(queryRfid.size()==0) {
                return false;
            }
        }
        return flag;
    }

}
